import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('userStore', () => {
        // State
        const token = ref('')
        const username = ref('')
        const userInfo = ref({})

        // Getters
        const isLogin = computed(() => !!token.value)
        const getToken = computed(() => token.value)
        const getUsername = computed(() => username.value)
        const getUserInfo = computed(() => userInfo.value)

        // Actions
        // 设置token
        const setToken = (newToken) => {
            token.value = newToken
        }

        // 设置用户名
        const setUsername = (name) => {
            username.value = name
        }

        // 设置用户信息
        const setUserInfo = (info) => {
            userInfo.value = info
            if (info.username) {
                username.value = info.username
            }
        }

        // 登录
        const login = (tokenValue, name = '') => {
            token.value = tokenValue
            if (name) {
                username.value = name
            }
        }

        // 登出
        const logout = () => {
            token.value = ''
            username.value = ''
            userInfo.value = {}
        }

        // 清除token
        const clearToken = () => {
            token.value = ''
            username.value = ''
            userInfo.value = {}
        }

        return {
            // state
            token,
            username,
            userInfo,
            // getters
            isLogin,
            getToken,
            getUsername,
            getUserInfo,
            // actions
            setToken,
            setUsername,
            setUserInfo,
            login,
            logout,
            clearToken,
        }
    },
    {
        // 持久化配置
        persist: {
            enabled: true,
            strategies: [
                {
                    key: 'user-store', // 存储的key名
                    storage: localStorage, // 存储方式：localStorage / sessionStorage
                    paths: ['token', 'username', 'userInfo'], // 需要持久化的字段
                },
            ],
        },
    }
)

